package com.JobWebGem.system.controller;

import com.JobWebGem.system.annotation.AuthCheck;
import com.JobWebGem.system.common.BaseResponse;
import com.JobWebGem.system.common.DeleteRequest;
import com.JobWebGem.system.common.ErrorCode;
import com.JobWebGem.system.common.ResultUtils;
import com.JobWebGem.system.constant.UserConstant;
import com.JobWebGem.system.exception.BusinessException;
import com.JobWebGem.system.exception.ThrowUtils;
import com.JobWebGem.system.model.dto.user.*;
import com.JobWebGem.system.model.entity.User;
import com.JobWebGem.system.model.vo.LoginUserVO;
import com.JobWebGem.system.model.vo.UserVO;
import com.JobWebGem.system.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.JobWebGem.system.constant.UserConstant.SALT;

/**
 * 用户接口
 *
 * @author renli
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户接口")
public class UserController {

    @Resource
    private UserService userService;

    // region 登录相关

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "用户注销")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @ApiOperation(value = "获取当前登录用户")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户(仅管理员)
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "创建用户(仅管理员)")
    public BaseResponse<Integer> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户(仅管理员)
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除用户(仅管理员)")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "更新用户（仅管理员）")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        User user = new User();
        if (userUpdateRequest.getUserAvatar() == null || userUpdateRequest.getUserAvatar().equals("")) {
            userUpdateRequest.setUserAvatar(user.getUserAvatar());
        }
        if (userUpdateRequest.getUserProfile() == null || userUpdateRequest.getUserProfile().equals("")) {
            userUpdateRequest.setUserProfile(user.getUserProfile());
        }
        if (userUpdateRequest.getUserName() == null || userUpdateRequest.getUserName().equals("")) {
            userUpdateRequest.setUserName(user.getUserName());
        }
        if (userUpdateRequest.getUserAccount() == null || userUpdateRequest.getUserAccount().equals("")) {
            userUpdateRequest.setUserAccount(user.getUserAccount());
        }
        if (userUpdateRequest.getUserPassword() != null && !userUpdateRequest.getUserPassword().equals("")) {
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userUpdateRequest.getUserPassword()).getBytes());
            userUpdateRequest.setUserPassword(encryptPassword);
        } else {
            userUpdateRequest.setUserPassword(user.getUserPassword());
        }
        if (userUpdateRequest.getUserRole() == null || userUpdateRequest.getUserRole().equals("")) {
            userUpdateRequest.setUserRole(user.getUserRole());
        }
        user.setId(Math.toIntExact(userUpdateRequest.getId()));

        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @return
     */
    @PostMapping("/get/vo")
    @ApiOperation(value = "根据 id 获取包装类")
    public BaseResponse<UserVO> getUserVOById(long id) {

        // 获取用户信息
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");

        // 将 User 对象转换为 UserVO 对象
        UserVO userVO = userService.getUserVO(user);
        return ResultUtils.success(userVO);
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @ApiOperation(value = "分页获取用户列表（所有人）")
    public BaseResponse<Page<UserVO>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest) {
        long current = userQueryRequest.getCurrent() == 0 ? 1 : userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize() == 0 ? 10 : userQueryRequest.getPageSize();

        Page<UserVO> pageParam = new Page<>(current, size);

        Page<UserVO> userPage = userService.pageByAdmin(pageParam, userQueryRequest);
        return ResultUtils.success(userPage);
    }

    // endregion

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    @ApiOperation(value = "更新用户个人信息")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest, HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        if (userUpdateMyRequest.getUserAvatar() == null || userUpdateMyRequest.getUserAvatar().equals("")) {
            userUpdateMyRequest.setUserAvatar(user.getUserAvatar());
        }
        if (userUpdateMyRequest.getUserProfile() == null || userUpdateMyRequest.getUserProfile().equals("")) {
            userUpdateMyRequest.setUserProfile(user.getUserProfile());
        }
        if (userUpdateMyRequest.getUserName() == null || userUpdateMyRequest.getUserName().equals("")) {
            userUpdateMyRequest.setUserName(user.getUserName());
        }
        if (userUpdateMyRequest.getUserAccount() == null || userUpdateMyRequest.getUserAccount().equals("")) {
            userUpdateMyRequest.setUserAccount(user.getUserAccount());
        }
        if (userUpdateMyRequest.getUserPassword() != null && !userUpdateMyRequest.getUserPassword().equals("")) {
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userUpdateMyRequest.getUserPassword()).getBytes());
            userUpdateMyRequest.setUserPassword(encryptPassword);
        } else {
            userUpdateMyRequest.setUserPassword(user.getUserPassword());
        }
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
}
